import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/cms/cmsmodel.dart';
import 'package:opene/ui/tally/tallymodel.dart';
import 'package:toast/toast.dart';

class CMSTallySubmitScreen extends StatelessWidget {
  CMSTally cmsTally;

  CMSTallySubmitScreen({
    this.cmsTally,
  });

  @override
  Widget build(BuildContext context) {
    return CMSTallySubmitScreenPage(cmsTally: cmsTally);
  }
}

class CMSTallySubmitScreenPage extends StatefulWidget {
  CMSTally cmsTally;

  CMSTallySubmitScreenPage({
    this.cmsTally,
  });

  @override
  _CMSTallySubmitScreenPageState createState() => _CMSTallySubmitScreenPageState(cmsTally: cmsTally);
}

class _CMSTallySubmitScreenPageState extends BaseState<CMSTallySubmitScreenPage> {
  CMSTally cmsTally;

  _CMSTallySubmitScreenPageState({
    this.cmsTally,
  });

  final controller = ScrollController();

  int index = 0, position;
  List<CMSTallyDetail> data = new List();
  List<CMSTallyDetail> tallyedData = new List();
  List<TallyDetail> tallyDetails = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Tally:Container";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        getTallyContainerNo();
      });
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, top: 10, right: 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 15, top: 5, right: 15, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 40),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (text == null) {
                    return;
                  }
                  inTallyTally(text);
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 25,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        inTallyTally(text);
                        print(text); //拿到扫描结果
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "product PalletLPN",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;

                },
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 10, left: 15, right: 15),
            child: Row(
              children: [
                Expanded(
                  flex: 1, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      if (type == 1) {
                        return;
                      }
                      setState(() {
                        type = 1;
                        textEditingController.text = "";
                        data.clear();
                        getTallyContainerNo();
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.all(5),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                        borderRadius: BorderRadius.only(topLeft: Radius.circular(8.0), bottomLeft: Radius.circular(8.0)), // 圆角半径
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue, // 边框颜色
                          width: 0.5, // 边框宽度
                        ),
                      ),
                      child: Text(
                        'LPN Type',
                        style: type == 1 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                      ), // 子控件，如果需要的话
                    ),
                  ),
                ),
                Expanded(
                  flex: 1, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      if (type == 2) {
                        return;
                      }
                      setState(() {
                        type = 2;
                        textEditingController.text = "";
                        data.clear();
                        getTallyContainerNo();
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.all(5),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                        borderRadius: BorderRadius.only(topRight: Radius.circular(8.0), bottomRight: Radius.circular(8.0)), // 圆角半径
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue, // 边框颜色
                          width: 0.5, // 边框宽度
                        ),
                      ),
                      child: Text(
                        ((cmsTallyedDetail == null) || (cmsTallyedDetail.total == null)) ? "Tallied(--)" : 'Tallied(${Utils.getStringisInteger(cmsTallyedDetail.total)})',
                        style: type == 2 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                      ), // 子控件，如果需要的话
                    ),
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 15, right: 10, top: 10),
              child: type == 1 ? setListView() : settallyedListView(),
            ),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        CMSTallyDetail tally = data[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                  flex: 2, //设置权重
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "${Utils.getStringisEmpty(tally.destination)}(${Utils.getStringisInteger(tally.num)})",
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          Text(
                            "QTY: ${Utils.getStringisInteger(tally.totalCtns)}",
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                          ),
                          Text(
                            "  Volume(m³): ${Utils.getStringisDouble(tally.totalVolume)}",
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                GestureDetector(
                  onTap: () {},
                  child: Container(
                    padding: EdgeInsets.all(3),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: MyAppTheme.nearlyBlue, // 背景颜色
                      borderRadius: BorderRadius.all(Radius.circular(5)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      "Print LPN",
                      style: MyAppTheme.captionWhite,
                    ), // 子控件，如果需要的话
                  ),
                ),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  ListView settallyedListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        CMSTallyDetail tally = tallyedData[index];
        if (tally.click == null) {
          tally.click = false;
        }
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                  flex: 3, //设置权重
                  child: Text(
                    Utils.getStringisEmpty(tally.destination),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                  ),
                ),
                Expanded(
                  flex: 2, //设置权重
                  child: Text(
                    Utils.getStringisInteger(tally.num),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      tally.click = !tally.click;
                      data[index] = tally;
                    });
                  },
                  child: Icon(
                    tally.click ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                    size: 20,
                    color: MyAppTheme.nearlyBlue,
                  ),
                ),
              ],
            ),
            Visibility(
                visible: tally.click ? true : false,
                child: Container(
                  margin: EdgeInsets.only(left: 5, top: 5),
                  child: setListViewItem(tally.inTallys),
                )),
            Divider(),
          ],
        );
      },
    );
  }

  ListView setListViewItem(List<CMSTallyDetailLpn> list) {
    return ListView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: list == null ? 0 : list.length,
      itemBuilder: (context, index) {
        CMSTallyDetailLpn lpnBean = list[index];
        return Row(
          children: [
            Expanded(
              flex: 1, //设置权重
              child: Text(
                Utils.getStringisEmpty(lpnBean.palletLpn),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
              ),
            ),
            Expanded(
              flex: 1, //设置权重
              child: Text(
                Utils.getStringisInteger(lpnBean.num),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
              ),
            ),
            GestureDetector(
              onTap: () {
                delete(lpnBean.id);
              },
              child: Icon(
                Icons.delete,
                size: 20,
                color: MyAppTheme.grey,
              ),
            ),
          ],
        );
      },
    );
  }

  @override
  void setNext() {
    ToastContext().init(context);
    if (Utils.isEmpty(textEditingController.text)) {
      Toast.show("Please input product PalletLPN", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    inTallyTally(textEditingController.text);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
    });
  }

  CMSTallyedDetail cmsTallyedDetail;
  List<CMSTallyDetail> cmsTallyDetails;

  void getTallyContainerNo() async {
    String url = Constants.fbaTransNotifyTallyGetNotifyPendingTally;
    if (type == 2) {
      url = Constants.fbaTransNotifyTallyGetNotifyTallyed;
    }
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    Map<String, dynamic> map = new HashMap();
    map["id"] = cmsTally.id;
    BaseResponse baseResponse = await NetworkManager().request(context, url,params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        switch (type) {
          case 1:
            cmsTallyDetails = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => CMSTallyDetail.fromJson(userJson)).toList());
            data = cmsTallyDetails;
            break;
          case 2:
            cmsTallyedDetail = CMSTallyedDetail.fromJson(baseResponse.data);
            data = cmsTallyedDetail.tallyedList;
            break;
        }
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }


  void delete(int id) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context,title: "delete...");
    } catch (e) {
      e.toString();
    }
    Map<String, dynamic> map = new HashMap();
    map["id"] = id;
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.fbaTransNotifyTallyGetNotifyTallyDelete,method: BaseMethod.delete,params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      getTallyContainerNo();
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void inTallyTally(String barcode) async {
    CMSTallySubmitQr containerTallyQr = new CMSTallySubmitQr();
    containerTallyQr.transNotifyId = cmsTally.id;
    containerTallyQr.containerNo=cmsTally.containerNo;
    containerTallyQr.palletLpn =barcode;
    // 显示加载中对话框
    LoadingIndicator.show(context,title: "Submit...");
    String json = jsonEncode(containerTallyQr);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.fbaTransNotifyTallyGetNotifyTallyTally, method: BaseMethod.post, data: json);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      getTallyContainerNo();
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }
}
